#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash freesurfer-7.2.0.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] && echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] && echo "请输入正确的安装路径" && exit 1

get_tensorflow()
{
cnt=1
number=10
while [ $cnt -lt $number ]
do
    set +e
    echo "正在下载tensorflow，时间较长，请耐心等待......"
    wget -c -P $buildpath https://github.com/lhelontra/tensorflow-on-arm/releases/download/v2.2.0/tensorflow-2.2.0-cp37-none-linux_aarch64.whl
    result_code=$?
    if [ $result_code -ne 0 ];then
        cnt=$[$cnt+1]
    else
        echo "下载tensorflow成功"
        break
    fi
done

if [ $cnt -eq $number ];then
    echo "下载tensorflow失败，请重新执行脚本"
    exit
fi
set -e 
}

get_freesurfer()
{
cnt=1
number=10
while [ $cnt -lt $number ]
do
    set +e
    echo "正在下载freesurfer，时间较长，请耐心等待......"
    git clone -b fs-7.2 https://github.com/freesurfer/freesurfer.git
    result_code=$?
    if [ $result_code -ne 0 ];then
        cnt=$[$cnt+1]
    else
        echo "下载freesurfer成功"
        break
    fi
done

if [ $cnt -eq $number ];then
    echo "下载freesurfer失败，请重新执行脚本"
    exit
fi
set -e 
}


buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit

set -e
get_tensorflow
cd $buildpath
get_freesurfer

#修改freesurfer依赖文件
cd $buildpath/freesurfer
sed -i '2,3s/^/#&/g' $buildpath/freesurfer/python/requirements-extra.txt
sed -i '8,10s/^/#&/g' $buildpath/freesurfer/python/requirements-extra.txt
sed -i "7ipystrum\nneurite\nvoxelmorph\n" $buildpath/freesurfer/python/requirements-extra.txt
sed -i '13s/vtkRenderingOpenGLModule/vtkRenderingOpenGL2Module/g' $buildpath/freesurfer/freeview/QVTK7/vtkGUISupportQtModule.h
#添加Cmake依赖文件路径
sed -i "2i set(PETSC_DIR \$ENV{PETSC_DIR})" cmake/FindPETSC.cmake
sed -i "2i set(ANN_DIR \$ENV{ANN_DIR})" cmake/FindANN.cmake
sed -i "2i set(ARMADILLO_DIR \$ENV{ARMADILLO_DIR})" cmake/FindArmadillo.cmake
sed -i "2i set(OpenCV_DIR \$ENV{OpenCV_DIR})" cmake/FindOpenCV.cmake
sed -i '9s/opencv opencv2/opencv2/g' cmake/FindOpenCV.cmake
sed -i '9s/include/opencv4/g' cmake/FindOpenCV.cmake
sed -i '9s/ NAMES/\/include\/ NAMES/g' cmake/FindOpenCV.cmake
sed -i "205i set(VTK_DIR \$ENV{VTK_DIR})" CMakeLists.txt
sed -i "149i set(ITK_DIR \$ENV{ITK_DIR})" CMakeLists.txt
#添加sse2neon头文件
wget -t 40 -c -P $buildpath/freesurfer/include https://github.com/DLTcollab/sse2neon/archive/refs/tags/v1.5.1.tar.gz
tar xf $buildpath/freesurfer/include/v1.5.1.tar.gz -C $buildpath/freesurfer/include/
cp $buildpath/freesurfer/include/sse2neon-1.5.1/sse2neon.h $buildpath/freesurfer/include/
sed -i "28s/#include <xmmintrin.h>/#include \"sse2neon.h\"/g" $buildpath/freesurfer/include/affine.h
sed -i "22s/#include <xmmintrin.h>/#include \"sse2neon.h\"/g" $buildpath/freesurfer/include/affine.hpp
#通过git-annex下载远程数据
git remote add datasrc https://surfer.nmr.mgh.harvard.edu/pub/dist/freesurfer/repo/annex.git
git fetch datasrc
git config --global user.email "test.com"
git config --global user.name "test"
$buildpath/git-annex.linux/git-annex get .
#Cmake设置
mkdir $buildpath/freesurfer_build
cd $buildpath/freesurfer_build
cmake ../freesurfer -DCMAKE_INSTALL_PREFIX=$installpath/freesurfer -DCMAKE_C_COMPILER=mpicc -DCMAKE_CXX_COMPILER=mpicxx -DCMAKE_Fortran_COMPILER=flang
for file in $(find . -name flags.make); do sed -i 's/-Werror//g' $file; done
for file in $(find . -name flags.make); do sed -i 's/-mfpmath=sse//g' $file; done
for file in $(find . -name flags.make); do sed -i 's/-fallow-invalid-boz//g' $file; done
for file in $(find . -name link.txt); do sed -i 's/-fallow-invalid-boz//g' $file; done
for file in $(find . -name link.txt); do sed -i 's/flang/flang -fno-fortran-main/g' $file; done

sed -i "56i execute_process(COMMAND bash -c \"$installpath/freesurfer/python/bin/python3 -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade --default-timeout=1000 --disable-pip-version-check $buildpath/tensorflow-2.2.0-cp37-none-linux_aarch64.whl --target=$installpath/freesurfer/python/packages\" RESULT_VARIABLE retcode)" python/cmake_install.cmake
sed -i '56s/^/    &/g' python/cmake_install.cmake
sed -i '57s/--upgrade/-i https:\/\/pypi.tuna.tsinghua.edu.cn\/simple --upgrade --default-timeout=1000/g' python/cmake_install.cmake
sed -i '43s/--upgrade/-i https:\/\/pypi.tuna.tsinghua.edu.cn\/simple --upgrade --default-timeout=1000/g' python/cmake_install.cmake
make -j$(nproc)
make install


cat >"$installpath/freesurfer/freesurfer_modulefiles" <<EOF
#%Module1.0
conflict freesurfer
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set FREESURFER \$pwd
setenv FREESURFER \$FREESURFER
prepend-path FREESURFER_HOME \$FREESURFER
EOF
rm -rf $buildpath/freesurfer
rm -rf $buildpath/freesurfer_build
